//
//  SetpSlider.swift
//  CustomSliderDemo
//
//  Created by IYE Technologies on 12/16/14.
//  Copyright (c) 2014 IYE Technologies. All rights reserved.
//

import UIKit

class StepSlider: UIControl {
    
    var trackView:UIImageView = UIImageView();
    var thumbView:UIImageView = UIImageView();
    var labels:[UILabel] = [];
    private var currentValue:Double = 2.0 {
        didSet{
            updateThumbViewPosition();
        }
    };
    
    var minValue:Double = 2.0{
        didSet{
            self.adjustLabels();
            setCurrentValue();
        }
    };
    
    var maxValue:Double = 6.0 {
        didSet{
            self.adjustLabels();
            setCurrentValue();
        }
    };
    
    var value:Double = 4.0 {
        didSet{
            setCurrentValue();
            updateThumbViewPosition();
        }
    };
    
    var font:UIFont = UIFont.boldSystemFontOfSize(12){
        didSet{
            self.adjustLabels();
        }
    }
    
    var suffix:String = ""{
        didSet{
            self.adjustLabels();
        }
    };
    
    required init(coder: NSCoder) {
        super.init(coder: coder);
    }
    
    
    init(frame:CGRect,track:String,thumb:String) {
        super.init(frame: frame);
        self.initSlider(track, thumb: thumb);
    }
    
    override func drawRect(rect: CGRect) {
        super.drawRect(rect);
        self.initSlider("track", thumb: "thumb");
    }
    
    func initSlider(track:String,thumb:String){
        self.backgroundColor = UIColor.clearColor();
        self.trackView.image = UIImage(named: track);
        self.trackView.sizeToFit();
        self.addSubview(self.trackView);
        
        self.thumbView.image = UIImage(named: thumb);
        self.thumbView.sizeToFit();
        self.addSubview(self.thumbView);
        
        self.frame.size.height = self.thumbView.frame.height * 2;
        
        self.trackView.frame.size.width = self.frame.width;
        var originY = (self.thumbView.frame.height - self.trackView.frame.height) / 2;
        self.trackView.frame.origin.y = originY;
        
        self.adjustLabels();
        updateThumbViewPosition();
    }
    
    func adjustLabels(){
        for label in labels{
            label.removeFromSuperview();
        }
        var lastX:CGFloat = 0;
        var maxValueAsInteger = NSDecimalNumber(double: maxValue).integerValue;
        var minValueAsInteger = NSDecimalNumber(double: minValue).integerValue;
        var label = UILabel();
        for(var i = 0; i <= maxValueAsInteger - minValueAsInteger; i++){
            label = UILabel();
            label.frame.origin.y = self.thumbView.frame.height + 5;
            label.text = "\(i + minValueAsInteger)\(suffix)";
            label.font = font;
            label.textColor = UIColor.whiteColor();
            label.sizeToFit();
            var lastX = perUnitWidth() * CGFloat(i) - label.frame.width / 2;
            lastX = min(max(lastX,0),self.frame.width - label.frame.width);
            label.frame.origin.x = lastX;
            self.addSubview(label);
            self.labels.append(label);
            
        }
        var firstLabel = self.labels.first! as UILabel;
        self.frame.size.height = firstLabel.frame.origin.y + firstLabel.frame.height;
    }
    
    func setCurrentValue(){
        self.currentValue  = value - minValue;
    }
    
    func updateThumbViewPosition() {
        let thumbCenter = CGFloat(positionForValue(currentValue) - Double(self.thumbView.frame.width / 2));
        CATransaction.begin()
        CATransaction.setDisableActions(true)
        thumbView.frame.origin = CGPoint(x: positionForValue(currentValue), y: 0.0);
        thumbView.setNeedsDisplay()
        CATransaction.commit();
    }
    
    func positionForValue(value: Double) -> Double {
        var unitWidth = perUnitWidth();
        var positionX = (Double(unitWidth) * value) - Double(self.thumbView.frame.width / 2);
        return min(max(positionX,0),Double(self.trackView.frame.width - self.thumbView.frame.width));
    }
    
    override func beginTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
        return true;
    }
    
    override func continueTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) -> Bool {
        var location = touch.locationInView(self);
        self.currentValue = Double(location.x / perUnitWidth());
        return true;
    }
    
    func perUnitWidth() -> CGFloat{
        return self.trackView.frame.width / CGFloat((maxValue - minValue));
    }
    
    override func endTrackingWithTouch(touch: UITouch, withEvent event: UIEvent) {
        var location = touch.locationInView(self);
        var numberHandler = NSDecimalNumberHandler(roundingMode: NSRoundingMode.RoundBankers, scale: 0, raiseOnExactness: false, raiseOnOverflow: false, raiseOnUnderflow: false, raiseOnDivideByZero: false);
        var decimalNumber = NSDecimalNumber(double: currentValue);
        self.currentValue = decimalNumber.decimalNumberByRoundingAccordingToBehavior(numberHandler).doubleValue;
        var actualValue = minValue + currentValue;
        self.value  = max(min(maxValue,actualValue),minValue);
        sendActionsForControlEvents(UIControlEvents.ValueChanged);
    }
}
